package com.knoya.chejian.pda.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Vibrator;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.knoya.chejian.pda.Myapp;
import com.knoya.chejian.pda.R;
import com.knoya.chejian.pda.activity.LoginActivity;
import com.knoya.chejian.pda.contacts.Contacts;
import com.knoya.chejian.pda.minterface.OnUserDataInterface;
import com.knoya.chejian.pda.mydialog.MyAlerDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/11/3 0003.
 * 作者：刘洋
 * 一些方便的方法的工具类
 */
public class Myutil {
    /**
     * 判断edittext是否为空
     */
    public static boolean isettrue(EditText et) {
        if (et.getText().toString().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    public static void  zhendong(Context context){
        Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
        vibrator.vibrate(1000);
    }

    public static boolean istvtrue(TextView tv) {
        if (tv.getText().toString().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    //Toast输出的方法
    public static void MyTost(String string) {
        Log.d("MyTost",string);
        Toast.makeText(Myapp.getContext(), string, Toast.LENGTH_LONG).show();
    }

    //Log打印的方法
    public static void Mylog(String TAG, String string) {
        Log.d(TAG, string);
    }

    // 使用Log来显示调试信息,因为log在实现上每个message有4k字符长度限制
    // 所以这里使用自己分节的方式来输出足够长度的message
    public static void longlogshow(String TAG, String str) {
        str = str.trim();
        int index = 0;
        int maxLength = 4000;
        String sub;
        while (index < str.length()) {
            // java的字符不允许指定超过总的长度end
            if (str.length() <= index + maxLength) {
                sub = str.substring(index);
            } else {
                sub = str.substring(index, maxLength + index);
            }
            index += maxLength;
            Log.d(TAG, sub.trim());
        }
    }

    //时间戳转换为yyyy-MM-dd HH:mm:ss格式
    public static String getdata(String s) {
        if (s == null) {
            return "null";
        }
        if(s.equals("0")){
            return  "";
        }
        String ss = s + "";
        if (ss.matches("[0-9]+")) {
            if (!ss.equals("null")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Long t = Long.valueOf(s);
                Date date = new Date(t * 1000);
                String time = format.format(date.getTime());
                return time;
            }
        } else {
            return ss;
        }
        return "";
    }

    public static Boolean isTel(String s){
        if (s.matches("[0-9]+")&&s.length()==11) {
            return true;
        }
        return false;
    }
    //时间戳转换为yyyy-MM-dd 格式
    public static String getdata1(String s) {
        if (s == null) {
            return "null";
        }
        String ss = s + "";
        if (ss.matches("[0-9]+")) {
            if (!ss.equals("null")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Long t = Long.valueOf(s);
                Date date = new Date(t * 1000);
                String time = format.format(date.getTime());
                return time;
            }
        } else {
            return ss;
        }
        return "";
    }
    /*
        * 将时间转换为时间戳
        */
    public static String dateToStamp(String s) {
        if(s.equals("")){
            return "";
        }
        String res="";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime()/1000;
            res = String.valueOf(ts);
        }catch (ParseException e){
            e.printStackTrace();
        }
        return res;
    }
    //判断输入textview的是句是否等于null
    public static void settv(String s, TextView tv) {
        if(tv==null){
            return;
        }
        if (s != null) {
            if (s.equals("null")) {
                tv.setText("");
            } else {
                tv.setText(s);
            }
        }else{
            tv.setText("");
        }
    }
    //判断输入editview的是句是否等于null
    public static void setet(String s, EditText tv) {
        if(tv==null){
            return;
        }
        if (s != null) {
            if (s.equals("null")) {
                tv.setText("");
            } else {
                tv.setText(s);
            }
        }else{
            tv.setText("");
        }
    }


    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @return
     */
    public static String Bitmap2StrByBase64(Bitmap bitmap, int yasuo) {
        if (yasuo > 100) {
            yasuo = 100;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, yasuo, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        bitmap.recycle();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }
    public static String encodeBase64File(String path) {
        File file = new File(path);
        byte[] buffer = new byte[0];
        try {
            FileInputStream inputFile = new FileInputStream(file);
            buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }
    /**
     * Unicode字符串转换
     *
     * @param theString
     * @return
     */
    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    /**
     * 如果软键盘显示则隐藏
     */
    public static void notjianpan(Context context, ImageView iv) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(iv.getWindowToken(), 0);
        }
    }
    public static void notjianpan(Context context, TextView iv) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(iv.getWindowToken(), 0);
        }
    }

    private static long getFileSize(File file)  {
        long size = 0;
        try {
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } else {
                file.createNewFile();
                Log.e("获取文件大小", "文件不存在!");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return size;
    }
    public static void getimg(Activity activity, String path) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

        float hh = dm.heightPixels;
        float ww = dm.widthPixels;
//        if(hh<1300){
//            hh=hh*2;
//            ww=ww*2;
//        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
        opts.inJustDecodeBounds = false;
        int w = opts.outWidth;
        int h = opts.outHeight;
        Log.d("TAAAG","w="+w+"   h="+h);
        int z;
        if(w>h){
            z=w;
        }else {
            z=h;
        }
//            int size = 0;
//            if (w <= ww && h <= hh) {
//                size = 1;
//            } else {
//                double scale = w >= h ? w / ww : h / hh;
//                double log = Math.log(scale) / Math.log(2);
//                double logCeil = Math.ceil(log);
//                size = (int) Math.pow(2, logCeil);
//            }
//        Log.d("TAAAG","size="+size);
        if (z > 2000 && z < 4000) {
            opts.inSampleSize = 2;
        } else if (z > 4000) {
            opts.inSampleSize = 4;
        } else if (z > 8000) {
            opts.inSampleSize = 4;
        } else {
            opts.inSampleSize = 1;
        }
        bitmap = BitmapFactory.decodeFile(path, opts);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
////        Log.d("TAAAG","大小="+baos.toByteArray().length/1024);
//        while (baos.toByteArray().length > 150 * 1024) {
//            if (quality <= 0) {
//                break;
//            }
//            baos.reset();
//            quality -= 10;
//            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
//        }
        try {
            baos.writeTo(new FileOutputStream(path));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bitmap.recycle();
            try {
                baos.flush();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getjulidate(int day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 格式化对象
        Date date = new Date(System.currentTimeMillis());
        if(day!=0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, day);
            date = calendar.getTime();
        }
        return sdf.format(date);
    }

    public static String getjulidate1(int day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 格式化对象
        Date date = new Date(System.currentTimeMillis());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        date = calendar.getTime();
        return sdf.format(date);
    }
    /**删除文件夹*/
    public static void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }

        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }
    /**删除文件夹内文件*/
    public static void deleteLfile(File file){
            if (file.isDirectory()) {
                File[] childFiles = file.listFiles();
                for (int i = 0; i < childFiles.length; i++) {
                    childFiles[i].delete();
                }
            }
    }
    //通过路径将图片转化为Bitmap
    public static Bitmap GetBitmap(String path, int w, int h)
    {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        BitmapFactory.decodeFile(path, opts);
        int width = opts . outWidth;
        int height = opts . outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (width > w || height > h) {
            scaleWidth = ((float) width) / w;
            scaleHeight = ((float) height) / h;
        }
        opts.inJustDecodeBounds = false;
        float scale = Math. max (scaleWidth, scaleHeight);
        opts.inSampleSize = (int) scale;
        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
                BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), w, h, true);
    }

    /**
     * 加载动画
     */
    public static AlertDialog showupdatedialog(Context context, String s, boolean top) {
        AlertDialog updatedialog = new AlertDialog.Builder(context).create();
        updatedialog.show();
        if (top) {
            updatedialog.getWindow().setGravity(Gravity.TOP);       //设置靠右对齐
        }
        WindowManager.LayoutParams lp = updatedialog.getWindow().getAttributes();
        lp.alpha = 1.0f;
        lp.dimAmount = 0.5f;      //设置黑暗度
        updatedialog.getWindow().setAttributes(lp);
        updatedialog.setCanceledOnTouchOutside(false);
        updatedialog.getWindow().setBackgroundDrawable(new ColorDrawable());
        updatedialog.getWindow().setContentView(R.layout.dialog_updata);
        ImageView iv_rotate =  updatedialog.findViewById(R.id.iv_rotate);
        Animation operatingAnim = AnimationUtils.loadAnimation(context, R.anim.rotate);
        LinearInterpolator lin = new LinearInterpolator();
        iv_rotate.startAnimation(operatingAnim);
        operatingAnim.setInterpolator(lin);
        TextView tv_dialogtv =  updatedialog.findViewById(R.id.tv_lodingtext);
        tv_dialogtv.setText(s);
        return updatedialog;
    }

    public static boolean onerror(String throwable, Activity activity) {
        if (throwable.contains("Access denied for user anonymous")) {
            MyTost("当前不是登录状态");
            Intent intent = new Intent(activity, LoginActivity.class);
            activity.startActivity(intent);
            Intent intent1 = new Intent();
            intent1.setAction(Contacts.BORADCAST_ACTION_EXIT);
            activity.sendBroadcast(intent1);//发送退出系统广播  每个接收器都会收到 调动finish（）关闭
            return true;
        } else if (throwable.contains("Access denied for user")) {
            nopermssion(activity);
            MyTost("没有权限获取");
            return true;
        }else if(throwable.contains("CSRF")){
            HttpUtil.getToken(activity, new OnUserDataInterface() {
                @Override
                public void onUserData(String data) {
                    try{
                        JSONObject jo = new JSONObject(data);
                        String token = JsonUtil.getvolue(jo,"token");
                        Sputil.editor("erp").putString("token", token).commit();
                        Myutil.MyTost("请再次尝试");
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                    Log.d("onUserData",data);
                }

                @Override
                public void onNot(String throwable) {
                    Log.d("onUserData",throwable);
                }
            });
            return true;
        }else if(throwable.contains("SocketTimeoutException")){
            httperrordiaog(activity,"网络访问超时");
            return true;
        }else if(throwable.contains("UnknownHostException")){
            httperrordiaog(activity,"网络无连接，请检查网络设置");
            return true;
        }
        return false;
    }

    public static AlertDialog nopermssion(final Context context) {
        AlertDialog updatedialog = new AlertDialog.Builder(context).create();
        updatedialog.show();
        WindowManager.LayoutParams lp = updatedialog.getWindow().getAttributes();
        lp.alpha = 1.0f;
        lp.dimAmount = 0.5f;      //设置黑暗度
        updatedialog.getWindow().setAttributes(lp);
        updatedialog.setCanceledOnTouchOutside(false);
        updatedialog.getWindow().setContentView(R.layout.dialog_permission);
        return updatedialog;
    }

    public static void httperrordiaog(Context context,String s){
        if(s.trim().equals("")){
            s="网络访问失败";
        }
        final MyAlerDialog myAlerDialog = new MyAlerDialog(context);
        myAlerDialog.start();
        myAlerDialog.setdata(s);
        myAlerDialog.setleft("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAlerDialog.dismiss();
            }
        });
        myAlerDialog.show();

    }
    /**提示弹窗*/
    public static void tishidialog(Context context,String s){
        AlertDialog.Builder dialog = new  AlertDialog.Builder(context);
        dialog.setTitle("提示");
        dialog.setMessage(s);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    /**提示弹窗*/
    public static void tishidismissdialog(Context context,String s,DialogInterface.OnDismissListener listener){
        AlertDialog.Builder dialog = new  AlertDialog.Builder(context);
        dialog.setTitle("提示");
        dialog.setMessage(s);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.setOnDismissListener(listener);
        dialog.show();

    }
}
